import { expect } from '@jest/globals';
import * as compressing from 'compressing';
import fsExtra from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {
    [ModuleTemplateType.EmptyAbility]: 1,
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble,
};

const testFun: (module?: string) => TestCaseFun = (module?: string) => async (project, taskConfig, record) => {
  const entryModulePath = project.getModule('entry').moduleRootPath();
  const featureModulePath = project.getModule('application').moduleRootPath();
  let featureEnable = false;
  let entryEnable = false;

  // 读取的 路径 path.resolve(project.getModule('entry').moduleRootPath(),'build-profile.json5');
  const bufferEntry =
    await fsExtra.readFile(path.resolve(entryModulePath, 'build-profile.json5'));
  const entryBuildProfileJson = JSON5.parse(bufferEntry.toString());
  entryEnable = entryBuildProfileJson.buildOptionSet[0].arkOptions.obfuscation.ruleOptions.enable;

  // 读取的 路径 path.resolve(project.getModule('feature').moduleRootPath(),'build-profile.json5');
  const bufferFeature =
    await fsExtra.readFile(path.resolve(featureModulePath, 'build-profile.json5'));
  const featureBuildProfileJson = JSON5.parse(bufferFeature.toString());
  featureBuildProfileJson.buildOptionSet[0].arkOptions.obfuscation.ruleOptions.files[0] = './test.txt';
  const json5Str = JSON5.stringify(featureBuildProfileJson);
  await fsExtra.writeFile(path.resolve(featureModulePath, 'build-profile.json5'), json5Str, 'utf8');
  // eslint-disable-next-line max-len
  await fsExtra.rename(path.resolve(featureModulePath, 'obfuscation-rules.txt'), path.resolve(featureModulePath, 'test.txt'));
  featureEnable = featureBuildProfileJson.buildOptionSet[0].arkOptions.obfuscation.ruleOptions.enable;

  // 分别在在entry和feature模块中的混淆文件中配置代码混淆规则
  const str = '\n-enable-toplevel-obfuscation\n-compact';
  await fsExtra.appendFile(path.resolve(featureModulePath, 'test.txt'), str);
  await fsExtra.appendFile(path.resolve(entryModulePath, 'obfuscation-rules.txt'), str);

  // buildMode为none时，选择build APP
  const projectRoot = project.projectRootPath();
  const commands = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp',

    // , ...(module ? { module: `${module}@default` } : {})
  });
  const result = await runHvigorAsync(projectRoot, commands);

  // entry和feature中得到混淆后的hap产物，查看备注中的js文件
  const entryBuffer = await fsExtra.readFile(path.resolve(entryModulePath,
    'build/default/cache/default/default@CompileArkTS/esmodule/release/entry/src/main/ets/pages/Index.ts'));
  const stringEntry = entryBuffer.toString().split('\n');
  const entryObfuscation: boolean = stringEntry.length > 2;

  const featureBuffer = await fsExtra.readFile(path.resolve(featureModulePath,
    'build/default/cache/default/default@CompileArkTS/esmodule/release/application/src/main/ets/pages/Index.ts'));
  const stringFeature = featureBuffer.toString().split('\n');
  const featureObfuscation: boolean = stringFeature.length > 2;

  // entry模块hap包的根路径下不含有文件obfuscation.txt
  await fsExtra.copyFile(path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned.hap'),
    path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned.zip'));
  // eslint-disable-next-line max-len
  await compressing.zip.uncompress(path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned.zip'),
    path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned'));
  const entryObfuscationExist =
    // eslint-disable-next-line max-len
    await fsExtra.pathExists(path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned/obfuscation-rules.txt'));

  // feature模块hap包的根路径下不含有文件obfuscation.txt
  // eslint-disable-next-line max-len
  await fsExtra.copyFile(path.resolve(featureModulePath, 'build/default/outputs/default/application-entry-default-unsigned.hap'),
    path.resolve(featureModulePath, 'build/default/outputs/default/application-entry-default-unsigned.zip'));
  // eslint-disable-next-line max-len
  await compressing.zip.uncompress(path.resolve(featureModulePath, 'build/default/outputs/default/application-entry-default-unsigned.zip'),
    path.resolve(featureModulePath, 'build/default/outputs/default/application-entry-default-unsigned'));
  const featureObfuscationExist =
    // eslint-disable-next-line max-len
    await fsExtra.pathExists(path.resolve(featureModulePath, 'build/default/outputs/default/application-entry-default-unsigned/test.txt'));

  const commandsClean = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'clean'
    , ...(module ? { module: `${module}@default` } : {})
  });
  await runHvigorAsync(projectRoot, commandsClean);

  const commandsSecond = initExecuteCommand({
    mode: 'module',
    buildMode: 'release',
    product: 'default',
    tasks: 'assembleHap'
    , ...(module ? { module: `${module}@default` } : {})
  });
  const resultSecond = await runHvigorAsync(projectRoot, commandsSecond);

  const commandsThird = initExecuteCommand({
    mode: 'project',
    product: 'default',
    buildMode: 'release',
    tasks: 'assembleApp'
  });
  const resultThird = await runHvigorAsync(projectRoot, commandsThird);

  // entry和feature中得到混淆后的hap产物，查看备注中的js文件
  const entryBufferSecond = await fsExtra.readFile(path.resolve(entryModulePath,
    'build/default/cache/default/default@CompileArkTS/esmodule/release/entry/src/main/ets/pages/Index.ts'));
  const stringEntrySecond = entryBufferSecond.toString().split('\n');
  const entryObfuscationSecond: boolean = stringEntrySecond.length > 2;

  const featureBufferSecond = await fsExtra.readFile(path.resolve(featureModulePath,
    'build/default/cache/default/default@CompileArkTS/esmodule/release/application/src/main/ets/pages/Index.ts'));
  const featureEntrySecond = featureBufferSecond.toString().split('\n');
  const featureObfuscationSecond: boolean = featureEntrySecond.length > 2;

  // entry模块hap包的根路径下不含有文件obfuscation.txt
  await fsExtra.copyFile(path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned.hap'),
    path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned.zip'));
  // eslint-disable-next-line max-len
  await compressing.zip.uncompress(path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned.zip'),
    path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned'));
  const entryObfuscationExistSecond =
    // eslint-disable-next-line max-len
    await fsExtra.pathExists(path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned/obfuscation-rules.txt'));

  // feature模块hap包的根路径下不含有文件obfuscation.txt
  // eslint-disable-next-line max-len
  await fsExtra.copyFile(path.resolve(featureModulePath, 'build/default/outputs/default/application-entry-default-unsigned.hap'),
    path.resolve(featureModulePath, 'build/default/outputs/default/application-entry-default-unsigned.zip'));
  // eslint-disable-next-line max-len
  await compressing.zip.uncompress(path.resolve(featureModulePath, 'build/default/outputs/default/application-entry-default-unsigned.zip'),
    path.resolve(featureModulePath, 'build/default/outputs/default/application-entry-default-unsigned'));
  const featureObfuscationExistSecond =
    // eslint-disable-next-line max-len
    await fsExtra.pathExists(path.resolve(featureModulePath, 'build/default/outputs/default/application-entry-default-unsigned/test.txt'));

  record.addStep('执行App编译构建', result);
  record.addStep('执行Hap编译构建', resultSecond);
  expect(entryEnable).toBe(true);
  expect(featureEnable).toBe(true);
  expect(entryObfuscation).toBe(false);
  expect(featureObfuscation).toBe(false);
  expect(entryObfuscationExist).toBe(false);
  expect(featureObfuscationExist).toBe(false);
  expect(entryObfuscationSecond).toBe(false);
  expect(featureObfuscationSecond).toBe(false);
  expect(entryObfuscationExistSecond).toBe(false);
  expect(featureObfuscationExistSecond).toBe(false);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  expect(resultSecond.stdout).toContain('BUILD SUCCESSFUL');
  expect(resultThird.stdout).toContain('BUILD SUCCESSFUL');


};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_ZOS_HOS_Build_App_Stage_ArkTS_obfuscation_002')
  .description('混淆默认开启时打hap包')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun('entry'))
  .load();
